package controllers

import (
	"IrisService/models"

	"github.com/jinzhu/gorm"
	"github.com/kataras/iris/v12"
)

type ChangeLog struct {
	*baseController
}

// 如果在 [] 运算符里指定了一个值，那么创建的就是数组而不是切片。
// 只有在 [] 中不指定值的时候，创建的才是切片
func NewChangeLog(db *gorm.DB) *ChangeLog {
	props := []string{
		"_apis",
		"all",
		"id/#id",
		"entries",
		"entry/#entry",
		"POST:"}
	item := &baseController{
		entry: "ChangeLog",
		db:    db,
		model: models.ChangeLogItem{},
		props: props}
	return &ChangeLog{item}
}

func (c *ChangeLog) GetIdBy(id uint) iris.Map {
	if id < 1 {
		return c.Fail()
	} else {
		item := new(models.ChangeLogItem)
		c.db.First(item, id)
		return c.Rise(item)
	}
}

func (c *ChangeLog) GetEntries() iris.Map {
	var items []string
	rows, _ := c.db.Table(c.model.TableName()).Select("entry").Group("entry").Rows()
	for rows.Next() {
		var item string
		rows.Scan(&item)
		items = append(items, item)
	}
	return c.GenTopics(items)
}

func (c *ChangeLog) GetEntryBy(entry string) iris.Map {
	if len(entry) == 0 {
		return c.Fail()
	} else {
		items := new([]models.ChangeLogItem)
		c.db.Where("entry=?", entry).Find(items)
		return c.GenTopic(entry, items)
	}
}

func (c *ChangeLog) GetAll() iris.Map {
	items := new([]models.ChangeLogItem)
	c.db.Find(items)
	return c.GenDetails(items)
}

func (c *ChangeLog) Post(ctx iris.Context) iris.Map {
	item := new(models.ChangeLogItem)
	if err := ctx.ReadJSON(item); err != nil {
		return c.Fail()
	} else {
		return c.Rise(c.db.Create(item).RowsAffected)
	}
}
